package net.lc7.curator;

import net.lc7.util.ZkPropertiesUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMultiLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.RetryNTimes;

import java.util.concurrent.TimeUnit;

/**
 * @Description: Curator操作zk实现分布式锁
 * @Author: Jason.zhu
 * @Create: 2019/05/27 11:28
 */

public class CuratorDistributeLock {
    private static String lockPath = "/lockPath";

    public static void main(String[] args) throws Exception{
        CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(ZkPropertiesUtil.getZkServerIp(),
                                                        new RetryNTimes(10,5000));
        curatorFramework.start();
        System.out.println("zk client start successfully!!");
        Thread.sleep(1000L);


        Thread t1 = new Thread(() -> {
           doWithLock(curatorFramework);
        }, "t1");

        Thread t2 = new Thread(() -> {
            doWithLock(curatorFramework);
        }, "t2");

        t1.start();
        t2.start();


//        curatorFramework.close();
    }

    private static void doWithLock(CuratorFramework curatorFramework){
        System.out.println("Client state : " + curatorFramework.getState());
        InterProcessMutex lock = new InterProcessMutex(curatorFramework, lockPath);

        try {
            if(lock.acquire(10*1000, TimeUnit.SECONDS)){
                System.out.println(Thread.currentThread().getName() + "hold lock!!");
                Thread.sleep(5000L);
                System.out.println(Thread.currentThread().getName() + "release lock!!");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                lock.release();
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }
}
